package com.coderly.onlinegallerysharingplatform.common.oss.template;

import cn.hutool.core.io.FileUtil;
import com.coderly.onlinegallerysharingplatform.common.convention.errorcode.ErrorCode;
import com.coderly.onlinegallerysharingplatform.toolkit.ExceptionTrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 图片文件上传行为
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {

    @Override
    protected void validPicture(Object pictureSource) {
        MultipartFile multipartFile = (MultipartFile) pictureSource;
        ExceptionTrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1.校验文件大小
        long fileSize = multipartFile.getSize(); // 以字节为单位
        final long ONE_M = 1024 * 1024;
        ExceptionTrowUtils.throwIf(fileSize > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件不能大于2MB");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");
        ExceptionTrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    @Override
    protected String getOriginalFilename(Object pictureSource) {
        MultipartFile multipartFile = (MultipartFile) pictureSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object pictureSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) pictureSource;
        multipartFile.transferTo(file);
    }
}
